package com.ruoyi.bl.tools;

import com.alibaba.dashscope.app.Application;
import com.alibaba.dashscope.app.ApplicationParam;
import com.alibaba.dashscope.app.ApplicationResult;
import com.ruoyi.bl.service.MemoryIdService;
import io.reactivex.Flowable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import java.io.IOException;

/**
 * 智能体活动介绍
 */
@CrossOrigin(origins = "*")
@Slf4j
@RestController
@RequestMapping("/aliyun")
public class ActivityAsk {
    @Autowired
    private MemoryIdService memoryIdService;

    /**
     * 调用百炼接口,生成智能问答
     *
     * @param
     * @return 返回流式输出
     * @throws Exception
     */
    @GetMapping(value = "/ask/{name}")
    public ResponseBodyEmitter ask(@PathVariable("name") String name) throws Exception {
        // 设置超时时间和响应头
        ResponseBodyEmitter emitter = new ResponseBodyEmitter(-1L); // 无限超时
        // 设置响应头
        emitter.send("\n"); // 发送一个初始换行符以启动连接
        ApplicationParam param = ApplicationParam.builder()
                .apiKey("sk-dd83a9bc21f5440491fe836b7aa33cee")//主机的apikey
                .appId("b9d0e2390bfd4415b2d8a8c5db22e372")//使用介绍活动的智能体
                .prompt("请介绍一下" + name + "这个活动吧")//prompt提示词
                .incrementalOutput(true)//是否使用流式输出,我记得是这个功能来着,有些忘记了
                .build();
        Application application = new Application();
        Flowable<ApplicationResult> result = application.streamCall(param);
        result.subscribe(
                data -> {
                    try {
                        String text = data.getOutput().getText();
                        System.out.println(text);
                        emitter.send(text);
                    } catch (IOException e) {
                        emitter.completeWithError(e);
                    }
                },
                error -> {
                    log.error("Stream error:", error);
                    emitter.completeWithError(error);
                },
                () -> {
                    try {
                        emitter.send("[DONE]");
                        emitter.complete();
                    } catch (IOException e) {
                        emitter.completeWithError(e);
                    }
                }
        );
        return emitter;
    }
}
